package com.wangc.report.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

@Service
public class SpringUtil implements ApplicationContextAware {
    private static final Logger logger = LoggerFactory.getLogger(SpringUtil.class);
    private static ApplicationContext applicationContext;

    /**
     * 获取applicationContext对象
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        applicationContext = arg0;
    }

    /**
     * 根据bean的id来查找对象
     *
     * @param id
     * @return
     */
    public static Object getBeanById(String id) {
        return applicationContext.getBean(id);
    }

    /**
     * 根据bean的class来查找对象
     *
     * @param c
     * @return
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static Object getBeanByClass(Class c) {
        return applicationContext.getBean(c);
    }

    /**
     * 根据bean的class来查找所有的对象(包括子类)
     *
     * @param c
     * @return
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static Map getBeansByClass(Class c) {
        return applicationContext.getBeansOfType(c);
    }

    /**
     * 从spring容器中取出Bean对象
     *
     * @param beanName Bean名称
     * @param required 是否必须取到Bean
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName, boolean required) {
        T o = null;
        try {
            o = (T) applicationContext.getBean(beanName);
        } catch (NoSuchBeanDefinitionException e) {
            if (required) {
                throw e;
            }
        }
        return o;
    }

    /**
     * 从spring容器中取出Bean对象
     *
     * @param beanName Bean名称
     * @return
     */
    public static <T> T getBean(String beanName) {
        return getBean(beanName, false);
    }

    /**
     * 从spring容器中取出Bean对象
     *
     * @param beanType Bean类型.
     * @param required 是否必须取到Bean
     * @return
     */
    public static <T> T getBean(Class<T> beanType, boolean required) {
        T o = null;
        try {
            o = applicationContext.getBean(beanType);
        } catch (NoUniqueBeanDefinitionException e) {
            Map<String, T> map = applicationContext.getBeansOfType(beanType);
            if (map != null) {
                if (map.size() > 1) {
                    logger.warn("too many bean with type " + beanType + " : " + map);
                    if (logger.isDebugEnabled()) {
                        for (Entry<String, T> entry : map.entrySet()) {
                            logger.debug("Bean(" + beanType + ") id:" + entry.getKey() + ", bean:" + entry.getValue().getClass());
                        }
                    }
                }
                Iterator<String> iter = map.keySet().iterator();
                if (iter.hasNext()) {
                    o = map.get(iter.next());
                }
            }
            if (o == null && required) {
                throw new NoSuchBeanDefinitionException("No qualifying bean of type [" + beanType + "] is defined");
            }
        } catch (NoSuchBeanDefinitionException e) {
            if (required) {
                throw e;
            }
        }
        return o;
    }

    /**
     * 从spring容器中取出Bean对象
     *
     * @param beanType Bean类型.
     * @return
     */
    public static <T> T getBean(Class<T> beanType) {
        return getBean(beanType, true);
    }
}